package com.eliota.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.eliota.entity.User;
import com.eliota.exception.CustomException;
import com.eliota.exception.GlobalExceptionHandler;
import com.eliota.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.undo.CannotUndoException;

/**
 * @author M.G
 * @create 2023-03-27 10:20
 * @date 2023/3/27 10:20
 */

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        String token = request.getHeader("token");
        //若不是映射到方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //请求token为空
        if(StrUtil.isBlank(token)){
            throw new CustomException(Constants.CODE_401,"无Token，请重新验证");
        }
        //获取token中的userid
        String userID;
        try{
            userID = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new CustomException(Constants.CODE_401,"token验证失败");
        }
        //编码解密id再次查询数据库中是否有该ID的用户，有的化返回对象
        User user = userService.getById(userID);
        if (user == null) {
            throw new CustomException(Constants.CODE_401,"用户不存在，请重新登录注册");
        }
        // 用户密码加签 验证
        // 用JWT再次对生成token的sign签证正向编码，请求对已生成的密码
        // verify比对方法
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);   // 验证token
        } catch (JWTVerificationException e) {
            throw new CustomException(Constants.CODE_401,"用户密码比对错误");
        }

        return true;
    }
}
